package com.xiaomage.ipcdemo

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log
import com.xiaomage.ipcdemo.Constants.MESSAGE_FROM_CLIENT
import com.xiaomage.ipcdemo.Constants.MESSAGE_FROM_SERVICE
import com.xiaomage.ipcdemo.Constants.MESSAGE_KEY
import com.xiaomage.ipcdemo.Constants.TAG
//服务端

class MessageService:Service() {
    private var handlerThread:HandlerThread?=null
    private var handler: Handler?=null

    private var messenger:Messenger?=null
    override fun onCreate() {
        super.onCreate()
        val pid=android.os.Process.myPid()
        Log.d(TAG, "进程ID：$pid")

        //HandlerThread使用Looper处理队列消息
        handlerThread= HandlerThread("message_service")
        handlerThread?.start()

        //获取Looper
        val looper=handlerThread?.looper


        //让Handler运行在HandlerThread中
        handler=object :Handler(looper){
            override fun handleMessage(msg: Message?) {
                //回复客户端消息
                replyToClientMsg(msg)
                super.handleMessage(msg)
            }
        }

        messenger= Messenger(handler)

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG,"onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }
    override fun onBind(intent: Intent?): IBinder {
        Log.d(TAG,"onBind")
       return messenger!!.binder
    }
    private fun replyToClientMsg(message: Message?){
        when(message?.what){

            MESSAGE_FROM_CLIENT->{
                //模拟服务器响应过程
                Log.d(TAG,"msg what=[${message?.what}]")
                Log.d(TAG,"msg arg1=[${message?.arg1}]")
                Log.d(TAG,"msg arg2=[${message?.arg2}]")

                Log.d(TAG,"客户端发送的消息${message?.data.getString(MESSAGE_KEY)}")

                //客户端回调
                val messengerFromClient =message?.replyTo

                val messageFromService=Message.obtain(null,MESSAGE_FROM_SERVICE)
                val bundle=Bundle()
                bundle.putString(MESSAGE_KEY,"我也爱你")
                messageFromService.data=bundle
                messengerFromClient.send(messageFromService)
            }
        }
    }
}